package com.changgou.canal.listener;


import com.alibaba.otter.canal.protocol.CanalEntry;
import com.xpand.starter.canal.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

@CanalEventListener
public class CanalDataEventListener {

    @Autowired
    private RestTemplate restTemplate;

    /***
     * 增加数据监听
     * eventType:操作类型，增删改
     * rowData:操作的数据
     */
    //@InsertListenPoint
    public void onEventInsert(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        //rowData.getAfterColumnsList() :获取所有列操作后的信息
        //rowData.getBeforeColumnsList();  获取所有列操作之前的信息
        for (CanalEntry.Column column : rowData.getAfterColumnsList()) {
            System.out.println("增加---->列名：" + column.getName() + "=" + column.getValue());
        }
    }

    /***
     * 修改数据监听
     */
    //@UpdateListenPoint  //修改数据节点监听
    public void onEventUpdate(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        //rowData.getAfterColumnsList() :获取所有列操作后的信息
        //rowData.getBeforeColumnsList();  获取所有列操作之前的信息

        //循环操作数据
        for (CanalEntry.Column column : rowData.getAfterColumnsList()) {
            System.out.println("修改---->列名：" + column.getName() + "=" + column.getValue());
        }
    }


    /****
     * 删除数据监听
     */
    //@DeleteListenPoint  //删除数据节点监听
    public void onEventDelete(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        //rowData.getAfterColumnsList() :获取所有列操作后的信息
        //rowData.getBeforeColumnsList();  获取所有列操作之前的信息

        //循环操作数据
        for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
            System.out.println("删除---->列名：" + column.getName() + "=" + column.getValue());
        }
    }

    /****
     * 自定义监听
     * destination：canal配置文件中实例的名称
     * schema：指定监听哪个数据库
     * table：指定监听哪张表
     */
    @ListenPoint(destination = "example", schema = "changgou_content", table = {"tb_content"}, eventType = {CanalEntry.EventType.UPDATE, CanalEntry.EventType.INSERT})
    public void onEventCustomUpdate(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        //循环操作数据
        for (CanalEntry.Column column : rowData.getAfterColumnsList()) {
            System.out.println("修改--AAAA-->列名：" + column.getName() + "=" + column.getValue());
        }

        String id = rowData.getAfterColumnsList().get(1).getValue();
        String url = "http://192.168.206.130/update?id=" + id;
        String result = restTemplate.getForObject(url, String.class);
        System.out.println(result);
    }
}
